from pms.common.views import PostFormula
from department.models import Department, Work
from department.utils import department_view
from django.db.models.deletion import ProtectedError


class API(PostFormula):
    require_permissions = [14]

    def handle(self, req):
        try:
            department = Department.objects.get(id=req['id'])
            view = department_view(department)
            department.delete()
            return self.success_respond(view)
        except ProtectedError as e:
            protected_object = e.protected_objects.pop()
            if isinstance(protected_object, Work):
                return self.failed_respond('WORK_RID_PROTECT', '{}({})任职于该部门，故不能删除'
                                           .format(protected_object.uid.name, protected_object.uid_id))
